package com.ufo.store.management.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.utils.AnimationUtil;
import com.ufo.store.management.utils.Utils;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


/**
 * Created by taoli on 2017/12/5.
 */

public class PasswordFindActivity extends BaseActivity implements Handler.Callback {
    private ProgressBar myProgressBar;
    private TextView info_tv;
    private EditText searchip_et;
    private EditText searchuser_et;
    private EditText searchpassword_et;
    private Button searchip_bt;
    private Button searchpassword_bt;
    private TextView searchip_result_tv;
    private RadioGroup mRadioGroup;
    private Handler mHandler = null;
    private String ipFind = "";
    private String passwordFind = "";
    private String database = "isszmbalv3";    //fastfood

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 0:
                int num = (int) msg.obj;
                myProgressBar.setProgress(num);
                break;
            case 1:
                int num1 = (int) msg.obj;
                myProgressBar.setProgress(num1);
                break;
        }
        return true;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar);
        toolbar.setTitle("数据库找回");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.ic_back_selector);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initData() {
        mHandler = new Handler(this);
    }

    private void initView() {
        setContentView(R.layout.activity_passwordfind);
        myProgressBar = (ProgressBar) findViewById(R.id.myProgressBar);
        info_tv = (TextView) findViewById(R.id.info_tv);
        searchip_et = (EditText) findViewById(R.id.searchip_et);
        searchuser_et = (EditText) findViewById(R.id.searchuser_et);
        searchpassword_et = (EditText) findViewById(R.id.searchpassword_et);
        searchip_bt = (Button) findViewById(R.id.searchip_bt);
        searchpassword_bt = (Button) findViewById(R.id.searchpassword_bt);
        searchip_result_tv = (TextView) findViewById(R.id.searchip_result_tv);

        if (Utils.isNetworkConnected(getApplication()))
            info_tv.setText(Utils.getLocalIpAddress());

        mRadioGroup = (RadioGroup) findViewById(R.id.database_rg);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_isszmbalv3:
                        database = "isszmbalv3";
                        break;
                    case R.id.rb_fastfood:
                        database = "fastfood";
                        break;
                }
            }
        });

        searchip_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String searchip = searchip_et.getText().toString();
                if (Utils.isIP(searchip)) {
                    findIp();
                }else{
                    Toast.makeText(PasswordFindActivity.this, "Ip地址" + ipFind + "是非法地址！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        searchpassword_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String searchip = searchip_et.getText().toString();
                if (Utils.isIP(searchip) && !TextUtils.isEmpty(searchuser_et.getText().toString())) {
                    if (myProgressBar.getVisibility() == View.VISIBLE) {
                        Toast.makeText(PasswordFindActivity.this, "请等待搜索完！", Toast.LENGTH_SHORT).show();
                    } else {
                        findPassword();
                    }
                } else {
                    Toast.makeText(PasswordFindActivity.this, "Ip地址" + ipFind + "是非法地址或者数据库用户名为空！", Toast.LENGTH_SHORT).show();
                }
            }
        });

        LinearLayout content_ll = (LinearLayout) findViewById(R.id.content_ll);
        AnimationUtil.setTopToBottomAnimation(content_ll, 700, 0.1f);
    }

    private void findIp() {
        searchip_bt.setText("正在搜索");
        myProgressBar.setVisibility(View.VISIBLE);
        final String searchuser = searchuser_et.getText().toString();
        final String searchip = searchip_et.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                int curProgress = 0;
                Connection connect = null;
                String iplastChar = searchip.substring(searchip.lastIndexOf(".")+1,searchip.length());
                for (int i = Integer.parseInt(iplastChar); i <= 255; i++) {
                    int progress = ( i -  Integer.parseInt(iplastChar) ) * 100 / ( 255 - Integer.parseInt(iplastChar) ) ;
                    if (curProgress < progress) {
                        curProgress = progress;
                        Message _Msg = mHandler.obtainMessage(1, curProgress);
                        mHandler.sendMessage(_Msg);
                    }

                    try {
                        connect = DriverManager.getConnection("jdbc:jtds:sqlserver://" + searchip.substring(0, searchip.lastIndexOf(".")+1) + i + ":1433/" + database, searchuser, "");
                        if (connect != null) {
                        }
                    } catch (final SQLException e) {
                        String state = e.getSQLState();
                        if( state != null ){
                            if( state.equals("28000")){
                                ipFind = searchip.substring(0, searchip.lastIndexOf(".")+1) + i ;
                                PasswordFindActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (!TextUtils.isEmpty(ipFind)) {
                                            searchip_bt.setText("已找到服务器");
                                            searchip_et.setText(ipFind);
                                        } else {
                                            searchip_bt.setText("未找到服务器");
                                        }
                                    }
                                });
                            }else{
                                PasswordFindActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        searchip_result_tv.setText(e.getMessage());
                                    }
                                });
                            }
                        }
                    }

//                    try {
//                        Socket socket = new Socket();
//                        SocketAddress socketAddress = new InetSocketAddress(searchip + i, 1433);
//                        socket.connect(socketAddress, 50);
//                        socket.close();
//                        ipFind = searchip + i;
//                        PasswordFindActivity.this.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (!TextUtils.isEmpty(ipFind)) {
//                                    searchip_bt.setText("已找到服务器");
//                                    searchip_et.setText(ipFind);
//                                } else {
//                                    searchip_bt.setText("未找到服务器");
//                                }
//                            }
//                        });
//                    } catch (Exception e) {
//                    }
                }
                PasswordFindActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myProgressBar.setVisibility(View.GONE);
                        if (!TextUtils.isEmpty(ipFind)) {
                            searchip_bt.setText("已找到服务器");
                            searchip_et.setText(ipFind);
                        } else {
                            searchip_bt.setText("未找到服务器");
                        }
                    }
                });
            }
        }).start();
    }

    private void findPassword() {
        searchpassword_bt.setText("正在找回");
        myProgressBar.setVisibility(View.VISIBLE);
        final String searchuser = searchuser_et.getText().toString();
        final String searchip = searchip_et.getText().toString();
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean isFind = false;
                int num = 0;
                int curProgress = 0;
                Connection connect = null;
                for (int i = 0; i < 10; i++) {
                    for (int ii = 0; ii < 10; ii++) {
                        for (int iii = 0; iii < 10; iii++) {
                            for (int iiii = 0; iiii < 10; iiii++) {
                                String pas = String.valueOf(iiii) + String.valueOf(iii) + String.valueOf(ii) + String.valueOf(i);
                                num++;
                                int progress = num * 100 / 10000;
                                if (curProgress < progress) {
                                    curProgress = progress;
                                    Message _Msg = mHandler.obtainMessage(0, curProgress);
                                    mHandler.sendMessage(_Msg);
                                }
                                try {
                                    Class.forName("net.sourceforge.jtds.jdbc.Driver");
                                    connect = DriverManager.getConnection("jdbc:jtds:sqlserver://" + searchip + ":1433/" + database, searchuser, pas);
                                    if (connect != null) {
                                        passwordFind = pas;
                                        isFind = true;
                                        break;
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            if (isFind)
                                break;
                        }
                        if (isFind)
                            break;
                    }
                    if (isFind)
                        break;
                }
                PasswordFindActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        myProgressBar.setVisibility(View.GONE);
                        if (!TextUtils.isEmpty(passwordFind)) {
                            searchpassword_bt.setText("已找回数据库密码");
                            searchpassword_et.setText(passwordFind);
                        } else {
                            searchpassword_bt.setText("未找到数据库密码");
                        }
                    }
                });
            }
        }).start();
    }
}
